package com.rankeiot.compiler;

import com.caoccao.javet.exceptions.JavetException;
import com.caoccao.javet.interop.V8Runtime;
import com.caoccao.javet.interop.converters.JavetProxyConverter;
import com.caoccao.javet.values.primitive.V8ValueString;
import com.caoccao.javet.values.reference.V8ValueGlobalObject;
import com.caoccao.javet.values.reference.V8ValueObject;
import com.caoccao.javet.values.reference.V8ValuePromise;

import java.io.IOException;
import java.util.Map;

/**
 * Vue3 SFC 编译器
 */
public class VueCompiler extends V8Compiler{
    V8ValueObject compiler;
    public VueCompiler(){
        super("/template_compiler.min.js");
        try {
            compiler = runtime.getGlobalObject().get("compiler");
        } catch (JavetException e) {
            throw new RuntimeException(e);
        }
    }
    protected void doInit(V8Runtime runtime, StringBuilder code) throws JavetException {
        runtime.getGlobalObject().set("global",runtime.getGlobalObject());
        // runtime.getGlobalObject().set("VueCompiler",runtime.getGlobalObject().get("VueCompiler"));
        runtime.setConverter(new JavetProxyConverter());
        runtime.getGlobalObject().set("lesscp",new LessCompiler());
        code.append("function lessc(s){return lesscp.compile(s)};");
    }
    @Override
    public String compile(String source) {
        try {
            V8ValueString ret = compiler.invoke("sfc",source);
            String compiled_source = ret.getValue();
            return UglifyCompiler.getInstance().compile(compiled_source);
        } catch (JavetException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    private static VueCompiler instance;

    public static VueCompiler getInstance() {
        if(instance==null){
            instance=new VueCompiler();
        }
        return instance;
    }
    public static void closeInstance(){
        if(instance!=null){
            try {
                instance.close();
                instance=null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
